package xkp.lesson5;

public class TestThreadLocal {
    public static void main(String[] args) {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        //因为main这个值是在主线程中放入的，所以只能在主线程照片中获取
        threadLocal.set("main");
        System.out.println(threadLocal.get());
        MyThread1 myThread1 = new MyThread1(threadLocal);
        MyThread2 myThread2 = new MyThread2(threadLocal);
        myThread1.start();
        myThread2.start();

    }
}

class MyThread1 extends Thread{
    private ThreadLocal threadLocal;
    public MyThread1(ThreadLocal threadLocal){
        this.threadLocal = threadLocal;
    }
    @Override
    public void run() {
        Thread.currentThread().setName("MyThread1");
        threadLocal.set("MyThread1");
        //当线程运行起来后获取的只是自己放进去的值,不会获取到别的线程的内容
        System.out.println(threadLocal.get()+":------"+Thread.currentThread().getName());
    }
}


class MyThread2 extends Thread{
    private ThreadLocal threadLocal;
    public MyThread2(ThreadLocal threadLocal){
        this.threadLocal = threadLocal;
    }
    @Override
    public void run() {
        Thread.currentThread().setName("MyThread2");
        threadLocal.set("MyThread2");
        System.out.println(threadLocal.get()+":------"+Thread.currentThread().getName());
    }
}